var express = require('express');
var router = express.Router();
const { Category,Course } = require('../../models');
const { Op } = require('sequelize');

const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/* GET home page. */
router.get('/', async function (req, res, next) {
    try {

        const query = req.query;
        // 页和每页现实几条数据
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;

        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [['id', 'DESC']],
            offset: offset,
            limit: pageSize
        }
        if (query.name) {
            condition.where = {
                name: {
                    [Op.like]: `%${query.name}%`
                }
            }
        }
        const { count, rows } = await Category.findAndCountAll(condition);
        success(
            res,
            '查询分类列表成功',
            {
                category: rows,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 查询分类详情
router.get('/:id', async function (req, res, next) {
    try {
        const category = await getCategory(req);
        success(
            res,
            '查询分类成功',
            {category}
        )

    } catch (error) {
        failure(res, error)
    }
});


// 新建分类
router.post('', async function (req, res, next) {
    try {
        const body = filterBody(req.body)
        const category = await Category.create(body)
        success(
            res,
            '创建分类成功',
            {category}
        )
    } catch (error) {
        failure(res, error)
    }
});

// 删除分类
router.delete('/:id', async function (req, res, next) {
    try {
        const category = await getCategory(req);
        
        // 查询当前列是否有课程
        count = await Course.count({ where: { categoryId: req.params.id } });
        if (count > 0) {
            throw new Error('当前分类有课程，无法删除')
        }

        await category.destroy()
        success(
            res,
            '删除分类成功'
        )
    } catch (error) {
        failure(res, error)
    }
});

// 更新分类
router.put('/:id', async function (req, res, next) {
    try {
        const category = await getCategory(req);
        const body = filterBody(req.body)
        await category.update(body)
        success(
            res,
            '更新分类成功', {
                category
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 过滤body 和 name
const filterBody = (body)=>{
    return {
        name: body.name,
        rank: body.rank
    }
}


/**
 * 查询当前分类
 * @param {*} req 
 */
async function getCategory(req) {
    const { id } = req.params;
    const condition = {
        include: [
            { model: Course, as: 'courses'}
        ]
    }
    const category = await Category.findByPk(id,condition);
    if (!category) {
        throw new NotFoundError(`ID: ${id}的分类未找到`)
    }
    return category;
}

module.exports = router;
